// 引入API工具
const api = require('../../utils/api.js')

Page({
  data: {
    keyword: '',
    categoryId: '',
    equipmentList: [],
    loading: false,
    creditScore: 100 // 默认信用分
  },

  onLoad(options) {
    if (options.keyword) {
      this.setData({ keyword: options.keyword });
    }
    if (options.categoryId) {
      this.setData({ categoryId: options.categoryId });
    }
    
    // 加载装备列表
    this.loadEquipmentList();
    
    // 获取用户信用分
    this.loadCreditScore();
  },
  
  onShow() {
    // 页面显示时重新加载信用分，以防信用分变化
    this.loadCreditScore();
  },
  
  // 加载用户信用分
  loadCreditScore() {
    const creditScore = wx.getStorageSync('creditScore');
    if (creditScore) {
      this.setData({ creditScore });
    }
  },
  
  // 加载装备列表
  loadEquipmentList() {
    const { keyword, categoryId } = this.data;
    this.setData({ loading: true });
    
    api.getEquipmentList(keyword, categoryId)
      .then(res => {
        this.setData({
          equipmentList: res.data,
          allEquipmentList: res.data
        });
      })
      .catch(err => {
        console.error('获取装备列表失败', err);
      })
      .finally(() => {
        this.setData({ loading: false });
        wx.stopPullDownRefresh();
      });
  },

  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({ keyword });
    this.searchEquipment(keyword);
  },

  searchEquipment(keyword) {
    this.setData({ keyword });
    this.loadEquipmentList();
  },

  filterByCategory(categoryId) {
    this.setData({ categoryId });
    this.loadEquipmentList();
  },

  onBorrowTap(e) {
    const equipmentId = e.currentTarget.dataset.id;
    
    // 检查信用分
    if (this.data.creditScore < 60) {
      wx.showToast({
        title: '信用分不足',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    // 获取所选装备信息
    const selectedEquipment = this.data.equipmentList.find(item => item._id === equipmentId);
    
    if (!selectedEquipment) return;
    
    wx.showModal({
      title: '确认借用',
      content: `借用此装备将需要${selectedEquipment.creditRequired}信用分，是否确认？`,
      success: (res) => {
        if (res.confirm) {
          // 调用借用接口
          api.borrowEquipment(equipmentId)
            .then(res => {
              wx.showToast({
                title: '借用成功',
                icon: 'success'
              });
              
              // 刷新列表
              this.loadEquipmentList();
              
              // 跳转到订单详情
              setTimeout(() => {
                wx.switchTab({
                  url: '/pages/profile/profile'
                });
              }, 1500);
            })
            .catch(err => {
              console.error('借用失败', err);
            });
        }
      }
    });
  },

  onSearchFocus() {
    this.setData({ keyword: '' });
  },
  
  // 下拉刷新
  onPullDownRefresh() {
    this.loadEquipmentList();
  }
}); 